package basemodel

import (
	"database/sql/driver"
	"fmt"
	"strconv"
)

type BitField bool

func (t *BitField) MarshalJSON() ([]byte, error) {

	var value bool
	if *t {
		value = true
	} else {
		value = false
	}
	return []byte(strconv.FormatBool(value)), nil
}

func (t *BitField) UnmarshalJSON(data []byte) error {
	if string(data) == "null" {
		return nil
	}
	b, _ := strconv.ParseBool(string(data))

	if b {
		*t = true
	} else {
		*t = false
	}

	return nil
}

func (t *BitField) Value() (driver.Value, error) {
	if *t {
		return true, nil
	}
	return false, nil
}

func (t *BitField) Scan(v interface{}) error {
	value, ok := v.([]byte)
	if ok {
		if value[0] == 0x01 {
			*t = true
		} else {
			*t = false
		}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}
